package cn.jasonone.hm.netdisc.controller;

import cn.jasonone.hm.netdisc.consts.SystemConst;
import cn.jasonone.hm.netdisc.model.dto.HttpResult;
import cn.jasonone.hm.netdisc.model.dto.UserInfoDTO;
import cn.jasonone.hm.netdisc.model.dto.UserInfoITO;
import cn.jasonone.hm.netdisc.model.pojo.UserInfo;
import cn.jasonone.hm.netdisc.service.UserInfoService;
import cn.jasonone.hm.netdisc.util.ErrorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author Jason
 * @date 2020-07-23 14:42:53
 */
@Controller
@SessionAttributes({SystemConst.SESSION_LOGIN_STATUS})
@Slf4j
public class HomController {
	@Resource
	private UserInfoService userInfoService;
	
	@GetMapping
	public String home(){
		return "index";
	}
	
	@GetMapping("/login")
	public String login(){
		return "login";
	}
	
	@GetMapping("/register")
	public String register(){
		return "register";
	}
	@PutMapping("/register")
	@ResponseBody
	public HttpResult register(@Valid UserInfoITO userInfo, BindingResult br, HttpServletRequest req, Model model){
		if(br.hasErrors()){
			return HttpResult.create(400, "非法的参数").addAttribute("errors", ErrorUtil.parseErrors(br));
		}
		UserInfo where = new UserInfo();
		where.setAccount(userInfo.getAccount());
		if(!userInfoService.findAll(where).isEmpty()){
			return HttpResult.create(400, "账号已存在");
		}
		
		try{
			userInfoService.save(userInfo);
			return HttpResult.success("注册成功").addAttribute("home", req.getContextPath()+"/");
		}catch (Exception e){
			log.error("注册失败", e);
			return HttpResult.create(500, e.toString());
		}
	}
	
	@GetMapping("/logout")
	public String logout(SessionStatus status){
		status.setComplete();
		return "login";
	}
	
	@PostMapping("/login")
	public String login(UserInfoDTO userInfo, Model model){
		UserInfo login = userInfoService.login(userInfo);
		if(login == null){
			return "redirect:/login";
		}
		model.addAttribute(SystemConst.SESSION_LOGIN_STATUS, login);
		return "redirect:/";
	}
	
}
